#include "recode.h"
#include "ui_recode.h"

reCode::reCode(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::reCode)
{
    ui->setupUi(this);
}

reCode::reCode(QTcpSocket* s, QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::reCode)
{
    ui->setupUi(this);
    UIDesign::setButtonUI(ui->backButton);
    UIDesign::setButtonUI(ui->confirmButton);
    UIDesign::setLineEditUI(ui->userName);
    UIDesign::setLineEditUI(ui->passOld);
    UIDesign::setLineEditUI(ui->passAgain);
    UIDesign::setLineEditUI(ui->passNew);
    UIDesign::setTransparent(ui->label);
    UIDesign::setTransparent(ui->label_2);
    UIDesign::setTransparent(ui->label_3);
    UIDesign::setTransparent(ui->label_4);
    UIDesign::setWindowUI(ui->centralwidget);

    setWindowTitle("修改密码");
    setWindowOpacity(0.95);
    this->setFixedSize(this->width(), this->height());
    sock = s;
    disconnect(s, SIGNAL(readyRead()), 0, 0);
}


reCode::~reCode()
{
    delete ui;
}

void reCode::on_confirmButton_clicked()
{
    if(ui->userName->text()=="")
    {
        QMessageBox::information(this, "提示", "用户ID不能为空");
        return;
    }
    if(ui->passAgain->text()!=ui->passNew->text()){
            //新密码两边输入不同
        QMessageBox::information(this, "提示", "两次密码输入不统一，请重新输入");
        ui->passAgain->setText("");
        ui->passNew->setText("");
        return ;
     }
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(sock, SIGNAL(readyRead()), this, SLOT(recv()));
    QJsonObject request;
    request.insert("order", 3);
    request.insert("myid", ui->userName->text());
    QJsonObject data;
    data.insert("oldpwd", ui->passOld->text());
    data.insert("newpwd", ui->passNew->text());
    request.insert("data", data);
    qDebug() << "---------------------------------------";
    qDebug() << request;
    qDebug() << "data:\n";
    qDebug() << data;
    qDebug() << "---------------------------------------";
    QJsonDocument document;
    document.setObject(request);
    QByteArray byteRequest = document.toJson();
    sock->write(byteRequest);
}

void reCode::on_backButton_clicked()
{
    this->close();
    emit mainclose();
}

void reCode::recv()
{
    QByteArray byteRequest;
    byteRequest = sock->readAll();
    QJsonParseError err;
    QJsonDocument document = QJsonDocument::fromJson(byteRequest, &err);
    if(err.error == QJsonParseError::NoError)
    {
        QJsonObject request = document.object();
        QJsonValue Rstatus = request.value("status");
        bool status = Rstatus.toBool();
        qDebug() << "---------------------------------------";
        qDebug() << request;
        qDebug() << "---------------------------------------";
        if(status)
        {
            QMessageBox::information(this, "提示", "更改申请已发送。");
            this->close();
            emit mainclose();
        }
        else
        {
            QMessageBox::warning(this, "警告", "申请不被认可！");
        }
    }
    else QMessageBox::warning(this, "警告", "服务器下传失败");
}
